package com.online.web.service.Impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.online.web.domain.CallResponse;
import com.online.web.domain.CallScenario;
import com.online.web.domain.CallScene;
import com.online.web.domain.IntelligentCallParameters;
import com.online.web.service.IntelligentCallService;
import com.online.web.signature.AESUtils;
import com.online.web.signature.SignUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;
import java.util.Map;

/**
 * 智能电话服务impl
 *
 * @author xiangtianlei
 * @date 2023/08/10
 */
@Service
public class IntelligentCallServiceImpl implements IntelligentCallService {

    private static final Logger logger = LoggerFactory.getLogger(IntelligentCallServiceImpl.class);
    private static final String URL = "http://219.151.11.5:11002";

    private static final String TASK_API_ENDPOINT = "/minzheng/callTask";
    private static final String RESULT_API_ENDPOINT = "/minzheng/queryCallResult";
    private static final String SCENE_API_ENDPOINT = "/minzheng/queryActs";
    private static final String CREATE_SCENE_API_ENDPOINT = "/minzheng/createAct";
    /**
     * 私钥
     */
    private static final String PRIVATE_KEY = "1222222313123123123";
    private static final String APPID = "2021";


    @Autowired
    private RestTemplate restTemplate;

    /**
     * 任务执行
     *
     * @param parameters 参数
     * @param callScene  调用场景
     * @return {@link CallResponse}
     */
    @Override
    public CallResponse executeTask(IntelligentCallParameters parameters, CallScene callScene) {
        // 加密签名sign
        generateSign(parameters);
        // 加密参数
        encryptionParameters(parameters, callScene);
        // 调用第三方接口执行任务
        return restTemplate.postForObject(URL + TASK_API_ENDPOINT, parameters, CallResponse.class);
    }

    /**
     * 获取执行结果
     *
     * @param parameters 参数
     * @param taskIdList 任务id列表
     * @return 执行结果
     */
    @Override
    public CallResponse getExecutionResult(IntelligentCallParameters parameters, List<String> taskIdList) {
        // 生成签名sign
        generateSign(parameters);
        // 加密参数
        encryptionParameters(parameters, taskIdList);
        // 调用第三方接口获取执行结果
        return restTemplate.postForObject(URL + RESULT_API_ENDPOINT, parameters, CallResponse.class);
    }

    /**
     * 获取场景列表
     *
     * @return 场景列表
     */
    @Override
    public CallResponse getSceneList() {
        IntelligentCallParameters parameters = new IntelligentCallParameters(APPID, String.valueOf(System.currentTimeMillis() / 1000));
        // 加密签名sign
        generateSign(parameters);
        // 请求体
        ObjectMapper objectMapper = new ObjectMapper();
        String requestBody = null;
        try {
            requestBody = objectMapper.writeValueAsString(parameters).replace("timestamp", "timeStamp");
            System.out.println(requestBody);
        } catch (JsonProcessingException e) {
            e.getMessage();
        }
        // 请求头
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);
        // 封装请求实体
        HttpEntity<String> requestEntity = new HttpEntity<>(requestBody, headers);
        String body = restTemplate.exchange(URL + SCENE_API_ENDPOINT, HttpMethod.POST, requestEntity, String.class).getBody();
        return JSON.parseObject(body, new TypeReference<CallResponse>() {
        });
    }

    /**
     * 新建场景接口
     *
     * @param parameters 参数
     * @param callScene  场景对象
     * @return 新建场景的ID
     */
    @Override
    public CallResponse createScene(IntelligentCallParameters parameters, CallScenario callScene) {
        // 先生成sign
        generateSign(parameters);
        // 加密参数
        encryptionParameters(parameters, callScene);
        // 调用第三方接口创建新场景
        return restTemplate.postForObject(URL + CREATE_SCENE_API_ENDPOINT, parameters, CallResponse.class);
    }

    /**
     * 生成签名
     *
     * @param parameters 参数
     */
    private void generateSign(IntelligentCallParameters parameters) {
        Map<String, String> stringStringMap = SignUtils.convertToIntelligentCallParameters(parameters);
        String signature = SignUtils.generateSignature(stringStringMap, PRIVATE_KEY);
        parameters.setSign(signature);
    }

    /**
     * 加密参数
     */
    private void encryptionParameters(IntelligentCallParameters parameters, Object object) {
        ObjectMapper mapper = new ObjectMapper();
        String json = "";
        try {
            json = mapper.writeValueAsString(object);
        } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        String encryption = AESUtils.encryption(json, PRIVATE_KEY);
//        parameters.setParam(encryption);
    }

}
